package com.example.compass;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.text.Html;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    private ImageView imageView;
    private SensorManager manager;
    private TextView text_degree;
    private SensorListener listener = new SensorListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text_degree = this.findViewById(R.id.degree);
        imageView = this.findViewById(R.id.imageView);
        //保持屏幕常亮
        imageView.setKeepScreenOn(true);
        //通过getSystemService获得SensorManager实例对象
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        //通过SensorManager实例对象获得想要的传感器对象:参数决定获取哪个传感器
        Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        manager.registerListener(listener, sensor,
                SensorManager.SENSOR_DELAY_GAME);
        super.onResume();
    }

    @Override
    protected void onPause() {
        manager.unregisterListener(listener);
        super.onPause();
    }

    private final class SensorListener implements SensorEventListener {
        private float predegree = 0;

        //传感器监测方向改变
        public void onSensorChanged(SensorEvent event) {
            float degree = event.values[0];// 存放了方向值 90
            float a = (float)(Math.round(degree*10))/10;
            text_degree.setText(a+"°");
            if (a < 5 || a > 355)
                text_degree.setTextColor(0xffff7171);
            else
                text_degree.setTextColor(0xffffffff);
            /*
              RotateAnimation类：旋转变化动画类
              参数说明:
              fromDegrees：旋转的开始角度。
              toDegrees：旋转的结束角度。
              pivotXType：X轴的伸缩模式，可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。
              pivotXValue：X坐标的伸缩值。
              pivotYType：Y轴的伸缩模式，可以取值为ABSOLUTE、RELATIVE_TO_SELF、RELATIVE_TO_PARENT。
              pivotYValue：Y坐标的伸缩值
            */
            RotateAnimation animation = new RotateAnimation(predegree, -degree,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            //旋转过程持续时间
            animation.setDuration(200);
            //罗盘图片使用旋转动画
            imageView.startAnimation(animation);
            predegree = -degree;
        }

        //传感器精度的改变
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    }
}